exports.index = function(req, res) {

	var query   = getQueryString(req), 
		files   = null, 
		curFile = null, 
		count   = 0,
		dir     = "public/api";


	query.name || (query.name = 'index');

	if(query.action) saveFile();
	else 			 readDir(), readFile();
	function getQueryString(req){
		return require("querystring").parse(require("url").parse(req.url).query);
	}

	function readDir(){
	 	require('fs').readdir(dir, function(err, file){
	 		if(err) console.log(err);
	 		files = file.map(function(f){ return f.slice(0, -3) }), response();
		});  
	}

	function readFile(){
		require('fs').readFile(fileName(), function(err, file){
			if(err) console.log(err);
		    curFile = JSON.parse(file.toString()), response();
		});
	}

	function saveFile(){
		require("fs").writeFile(fileName(), getData(), function(err){
			if(err) console.log(err);
			var msg;
		    if(err) msg = '写文件操作失败';
		    else 	msg = '写文件操作成功';
		    res.json({'msg' : msg});
		});
	}

	function getData(){
		return JSON.stringify(req.body);
	}

	function fileName() {
		return dir + "/" + query.name + '.js';
	}

	function response(){
		if(++count === 2) res.render("configServer",{files: files, file : curFile, active : query.name});
	}

};

